#!/usr/bin/env ruby
require 'fileutils'
require 'yaml'

unless defined? ROR_SERVICE_ROOT
  ROR_SERVICE_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  $:.unshift(ROR_SERVICE_ROOT)
end

require 'container/mongrel_controller'
require 'system/restart_haproxy'

class ProvisioningMaster

  include FileUtils

  def initialize
    @config_dir = File.join(ROR_SERVICE_ROOT, 'config')
    template_dir = File.join(ROR_SERVICE_ROOT, 'container')
    @haproxy_conf_template = File.join(template_dir, 'haproxy.conf.template')
    @haproxy_conf = File.join(@config_dir, 'haproxy.conf')
    @vhost_map_template = File.join(template_dir, 'vhost.map.template')
    @vhost_map = File.join(@config_dir, 'vhost.map')
    @container_root = File.join(ROR_SERVICE_ROOT, 'ddis', config[:ddid].to_s, config[:domain].to_s)
    mkdir_p @container_root
    @container_root = Pathname.new(@container_root).realpath.to_s
  end

  def config
    @config ||= YAML.load_file(ARGV[0])
  end

  def domain_without_www
    config[:domain].sub(/^www\./, '')
  end

  def domain_with_www
    "www." + domain_without_www
  end

  def configure_haproxy
    File.open(@haproxy_conf, 'a') do |f|
      template = File.read(@haproxy_conf_template)
      f.puts
      f.puts eval('"'+template+'"')
    end
    puts 'haproxy configured'
  end

  def configure_apache
    File.open(@vhost_map, 'a') do |f|
        template = File.read(@vhost_map_template)
        f.puts
        f.puts eval('"'+template+'"')
    end
    puts 'apache configured'
  end

  def generate_mongrel_config
    servers = [config[:app_vm1]]
    ports = config.select{|key, value| key.to_s =~ /^app_port(\d)+$/}.map{|pair| pair.last}.sort

    mongrel_controller = MongrelController.new(@container_root)
    mongrel_controller.create_container(servers, ports)

    sites_config_index = File.join(@config_dir, 'sites')
    mkdir_p sites_config_index

    ln_s @container_root, File.join(sites_config_index, config[:domain])
    puts 'mongrel configured'
  end

  def reload_servers
    system 'monit reload'
    HAProxyController.new.restart
  end

  def provision
    configure_haproxy
    configure_apache
    generate_mongrel_config
    reload_servers
  end

end

if $0 == __FILE__
  ProvisioningMaster.new.provision
end
